package com.hotau.product;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import android.graphics.Bitmap;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TextView;

import com.hotau.HotauActivity;
import com.hotau.HotauConstants;
import com.hotau.R;
import com.hotau.framework.SearchBarVisible;
import com.hotau.location.LocationUtil;
import com.hotau.location.WebImageView;
import com.hotau.location.WebImageView.ImageListener;
import com.hotau.product.vo.Product;
import com.hotau.ui.Pull2RefreshView;
import com.hotau.ui.Pull2RefreshView.OnRefreshListener;

public class ProductListFragment extends Fragment implements SearchBarVisible,
		OnItemClickListener, ImageListener, OnRefreshListener {

	private List<Product> productList;

	private boolean isSearchNearBy;

	private int radius = 10000;

	private static final int SORT_NONE = 0;
	private static final int ASC = 1;
	private static final int DSC = 2;

	private int sortPriceType = SORT_NONE;
	private int sortRateType = SORT_NONE;

	private String keyword;

	private ProductComparator productComparator;

	private ProductAdapter productAdapter;
	private Spinner distanceSpinner;
	private Spinner priceSpinner;
	private Spinner rateSpinner;
	private ListView productListView;

	private Pull2RefreshView pull2RefreshView;
	private LocationUtil locationUtil;

	private int pageNo = 1;
	private int totalPageNo = pageNo;

	private static final int[] RADIUS = { 10000, 500, 1000, 5000, 10000 };

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initData();
		productComparator = new ProductComparator();

		setHasOptionsMenu(true);

		priceSpinner = (Spinner) this.getActivity().findViewById(R.id.product_price_spinner);
		this.setSpinnerAdapter(priceSpinner, R.array.location_prices_sort,
				android.R.layout.simple_spinner_item);
		
		rateSpinner = (Spinner) this.getActivity().findViewById(R.id.product_rate_spinner);
        this.setSpinnerAdapter(rateSpinner, R.array.location_rating_sort, 
        		android.R.layout.simple_spinner_item);
        
        pull2RefreshView = (Pull2RefreshView) this.getActivity().findViewById(R.id.product_list_view);
        pull2RefreshView.setRefreshListener(this);
        pull2RefreshView.enableRefresh(false);
        productListView = pull2RefreshView.getListView();
        productListView.setCacheColorHint(0);
        productListView.setDivider(this.getActivity().getResources().getDrawable(R.drawable.location_item_split));
        productListView.setOnItemClickListener(this);
        if(productList == null) {
            this.productList = new ArrayList<Product>();
            if(isSearchNearBy){
                this.searchNearBy();
            } else {
                searchByKeyword();
            }
        } else {
            pull2RefreshView.hasMore(pageNo < totalPageNo);
        }
        productAdapter = new ProductAdapter();
        productListView.setAdapter(productAdapter);
        
        distanceSpinner = (Spinner) this.getActivity().findViewById(R.id.product_distance_spinner);
        if(isSearchNearBy) {
            this.setSpinnerAdapter(distanceSpinner,  R.array.location_distances,
                android.R.layout.simple_spinner_item);
        }
	}
	
    @Override
    public void onRefresh(){
        // TODO Auto-generated method stub
    }

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		return inflater.inflate(R.layout.product__list, container, false);
	}

	class ProductComparator implements Comparator<Product> {
		@Override
		public int compare(Product lhs, Product rhs) {
			int priceOffset = (int) (lhs.getActualPrice() - rhs
					.getActualPrice());
			int rateOffset = lhs.getRateCount() - lhs.getRateCount();

			if (SORT_NONE == sortPriceType) {
				if (ASC == sortRateType) {
					rateOffset = -rateOffset;
				}
				return rateOffset;
			} else {
				if (ASC == sortPriceType) {
					priceOffset = -priceOffset;
				}
				return priceOffset;
			}
		}
	}

	private void setSpinnerAdapter(Spinner spinner, int resId, int layoutResId) {
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this.getActivity(), resId, layoutResId);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View arg1,
					int position, long arg3) {
				if (parent.getId() == R.id.product_distance_spinner) {
					if (isSearchNearBy) {
						if (RADIUS[position] != radius) {
							radius = RADIUS[position];
						}
					}
					sortPriceType = SORT_NONE;
					sortRateType = SORT_NONE;
				} else if (parent.getId() == R.id.product_price_spinner) {
					if (sortPriceType != position) {
						sortRateType = SORT_NONE;
					}
				} else {
					if (sortRateType != position) {
						sortPriceType = SORT_NONE;
					}
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void initData() {

		Bundle bundleData = this.getArguments();
		if (bundleData != null)
			this.keyword = bundleData.getString("keyword");

		isSearchNearBy = true;
	}

	class ProductAdapter extends BaseAdapter {
		
		@Override
		public int getCount() {
			return productList.size();
		}

		@Override
		public Object getItem(int position) {
			return productList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder = null;
			if (convertView == null) {
				convertView = LayoutInflater.from(getActivity()).inflate(
						R.layout.product__item, null);
				holder = new ViewHolder();
				holder.iconView = (WebImageView) convertView.findViewById(R.id.product_item_icon);
				holder.iconView.setImageListener(ProductListFragment.this);
				holder.titleView = (TextView) convertView.findViewById(R.id.product_item_title);
				holder.priceView = (TextView) convertView.findViewById(R.id.product_item_price);
				holder.priceHintView = (TextView) convertView.findViewById(R.id.product_item_price_hint);
				holder.distanceView = (TextView) convertView.findViewById(R.id.product_item_distance);
				holder.ratingBar = (RatingBar) convertView.findViewById(R.id.product_item_rate);
				holder.promoteView = (ImageView) convertView.findViewById(R.id.product_item_promote);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			Product product = (Product) this.getItem(position);
			holder.titleView.setText(product.getProductName());
			holder.priceHintView.setText("价格");
			holder.priceView.setText("￥" + product.getActualPrice());

			if (isSearchNearBy) {
				if (product.getDistance() != null && product.getDistance() >= 0) {
					holder.distanceView.setText(String.format("%d", product.getDistance()) + "m");
				}
			}

			holder.promoteView.setVisibility(View.GONE);

			if (StringUtils.isNotBlank(product.getLogoPicture())) {
				holder.iconView.setImageFromURL(generateImageUrl(product.getLogoPicture()));
			} else {
				holder.iconView.setImageFromURL(product.getLogoPicture());
			}

			holder.ratingBar.setRating(product.getRateCount());
			return convertView;
		}

		class ViewHolder {
			WebImageView iconView;
			TextView titleView;
			RatingBar ratingBar;
			TextView priceView;
			TextView priceHintView;
			TextView distanceView;
			ImageView promoteView;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Product product = productList.get(position);
		Bundle bundle = new Bundle();
		bundle.putSerializable("product", product);
		Fragment fragment = new ProductDetailFragment();
		fragment.setArguments(bundle);
		
		HotauActivity csmbpActivity = (HotauActivity)getActivity();
		csmbpActivity.pushFragment("宝贝详情", fragment);
	}

	private String generateImageUrl(String file) {
		if (file.startsWith("/")) {
			file = file.substring(1);
		}

		String[] names = file.split("/");
		file = file.substring(0, file.lastIndexOf(names[names.length - 1]));

		String fileUrl = HotauConstants.HOTAU_HOST_ROOT_URL
				+ file.concat(URLEncoder.encode(names[names.length - 1]));
		Log.d("mytag", "image url: " + fileUrl);

		return fileUrl;
	}

	@Override
	public void onImageLoaded(WebImageView im, Bitmap bm, String url) {
		productAdapter.notifyDataSetChanged();
	}

    private void searchNearBy() {
    	productList.add(new Product("1", "口水鸡", null, 30, 0, 10, 3, null));
    	productList.add(new Product("2", "口水鸡", null, 30, 0, 10, 3, null));
    	productList.add(new Product("3", "口水鸡", null, 30, 0, 10, 3, null));
    	productList.add(new Product("4", "口水鸡", null, 30, 0, 10, 3, null));
    	productList.add(new Product("5", "口水鸡", null, 30, 0, 10, 3, null));
    	productList.add(new Product("6", "口水鸡", null, 30, 0, 10, 3, null));
    	productList.add(new Product("7", "口水鸡", null, 30, 0, 10, 3, null));
    	productList.add(new Product("8", "口水鸡", null, 30, 0, 10, 3, null));
    }
    
    private void searchByKeyword() {
    	
    }
	
    private Location getLastKnownLocation() {
        if(locationUtil == null) {
            locationUtil = LocationUtil.getInstance(getActivity());
        }
    	return locationUtil.requestLocation();
    }
    
	private double[] getCurrentLocation() {
		Location location = this.getLastKnownLocation();

		if (location == null) {
			location = locationUtil.getLastKnownLocation();
		}

		if (location != null) {
			double latitude = location.getLatitude();
			double longitude = location.getLongitude();
			return new double[] { latitude, longitude };
		}

		return null;
	}
	
	@Override
    public void onLoadingMore() {
        this.pageNo ++;
        if(isSearchNearBy) {
            this.searchNearBy();
        } else {
            searchByKeyword();
        }
    }
}
